<template>
  <view>
    <view class="submit" :style="'bottom:calc(' + (inputBottom ) + 'px)'">
      <view class="submit-chat">
        <!-- <view class="bt-img" @tap="records">
          <image :src="toc"></image>
        </view> -->
        <!-- 文本框 -->
        <my-textarea :class="['chat-input', lines,'chat-send']" :value.sync="msg" :replace="false" :clearDisabled="true"
          :focus="false" @focus="focus" @blur="blur" @board-change="handleBoardChange" :holdKeyboard="true"
          :placeholder="connecting?'正在连接小览中...':'请输入您想要问我的信息'" :confirmType="confirmType" @handleSend="inputs"
          :disabled="connecting" @line-change="handleLinechange" :textAreaStyle="textAreaStyle"
          :style="{height:myTextAreaHeight+'rpx'}" @update:value="updateInputValue($event,item)">
        </my-textarea>
        <!-- <view class="record btn" :class="{displaynone:!isrecord}" @touchstart="touchstart" @touchend="touchend"
          @touchmove="touchmove">
          按住说话
        </view> -->
        <view class="sendBtn" @click="handleStop" v-if="loading">
          <text class="icon icon-stop"></text>
        </view>
        <view class="sendBtn" @click="inputs" v-else-if="msg&&!loading">
          <text class="icon icon-send">发送</text>
        </view>
        <view class="sendBtn" @click="more" v-else>
          <text class="icon icon-more"></text>
        </view>
        <!-- <view class="bt-img" @tap="more">
          <image src="../../static/icon/news.png"></image>
        </view> -->
      </view>
      <!-- 表情 -->
      <!-- <view class="emoji" :class="{displaynone:!isemoji}">
        <view class="emoji-send">
          <view class="emoji-send-det" @tap="emojiBack">
            <image src="../../static/icon/leftbrackets.png"></image>
          </view>
          <view class="emoji-send-bt" @tap="emojiSend">发送</view>
        </view>
        <emoji @emotion="emotion" :height="260"></emoji>
      </view> -->
      <!-- 更多 -->
      <view class="more" :class="{displaynone:!ismore,higherMore:isUsualProblems}">
        <template v-if="isUsualProblems">
          <view class="backToMore">
            <u-icon name="arrow-left" @click="handleBackToMore"></u-icon>
          </view>
          <view class="problemList">
            <p class="problemItem" v-for="item,index in usualProblemList" :key="index"
              @click="handleUsualProblemItemClick(item)">{{item.title}}</p>
          </view>
        </template>
        <template v-else>
          <view class="more-list" @click="handleUsualProblem">
            <view class="moreImageContainer">
              <image
                src="https://upload.yl1001.com/upload/images/view?file=7twCK70N2VQsIv2YtQ5=-QuD_iXXhETfugi=hBoehzpy,CieTNdosHRC,f0FT.png">
              </image>
            </view>
            <view class="more-list-title">常见问题</view>
          </view>
        </template>
        <!-- <view class="more-list" @tap="sendImg('album')">
          <image src="../../static/icon/noreceive.png"></image>
          <view class="more-list-title">常见问题</view>
        </view> -->
        <!-- <view class="more-list" @tap="sendImg('camera')">
          <image src="../../static/icon/noreceive.png"></image>
          <view class="more-list-title">拍照</view>
        </view>
        <view class="more-list" @tap="choseLocation">
          <image src="../../static/icon/noreceive.png"></image>
          <view class="more-list-title">定位</view>
        </view>
        <view class="more-list">
          <image src="../../static/icon/noreceive.png"></image>
          <view class="more-list-title">视频</view>
        </view>
        <view class="more-list">
          <image src="../../static/icon/noreceive.png"></image>
          <view class="more-list-title">文件</view>
        </view> -->
      </view>
    </view>
    <!-- <view class="voice-bg" :class="{displaynone:!voicebg}">
      <view class="voice-bg-len">
        <view class="voice-bg-time" :style="{width:vlength/0.6+'%'}">
          {{vlength}}″
        </view>
        <view class="voice-del">上滑取消录音</view>
      </view>
    </view> -->
  </view>
</template>

<script>
// 引入组件
// import emoji from "./emoji.vue";
import MyTextarea from "./ElanwBotTextarea";
// 录音
const recorderManager = uni.getRecorderManager();

export default {
  data() {
    return {
      isrecord: false,
      isemoji: false,
      ismore: false,
      voicebg: false,
      pageY: 0,
      msg: "",
      // 直接引用地址可能出不来，需要用require
      toc: "https://img3.job1001.com/ypMp/elan/images/common/empty.png",
      timer: "", //计时器
      vlength: 0,
      isUsualProblems: false,
      inputBottom: 0,
      isIOS: uni.getSystemInfoSync().platform == "ios",
      confirmType: "done",
      textAreaStyle: 80,
      myTextAreaHeight: 88,
      // 当前输入内容的行数
      currentContentLineNum: 0,
    };
  },
  props: {
    loading: {
      type: Boolean,
      default: false,
    },
    connecting: {
      type: Boolean,
      default: false,
    },
    usualProblemList: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    // emoji,
    MyTextarea,
  },
  watch: {
    msg(newValue, oldValue) {
      if (newValue) {
        this.confirmType = "send";
      } else {
        this.confirmType = "done";
      }
    },
  },
  created() {
    this.$bus.$on("touchToCloseMore", () => {
      this.isUsualProblems = false;
      this.ismore = false;
    });
    this.getElementHeight();
  },
  beforeDestroy() {
    this.$bus.$off("touchToCloseMore");
  },
  methods: {
    refreshTextAreaHeight(lineCount) {
      this.currentContentLineNum = lineCount;
      if (lineCount > 1) {
        this.textAreaStyle = 190;
        this.myTextAreaHeight = 190;
      } else {
        this.textAreaStyle = 80;
        this.myTextAreaHeight = 88;
      }
    },

    // 监听输入框内容
    updateInputValue(e, item) {
      var lineCount = this.computeTextAreaLineNum(e);
      console.log("lineCount = " + lineCount);
      if (this.currentContentLineNum == lineCount) {
        return;
      }
      this.refreshTextAreaHeight(lineCount);
    },

    // 计算编辑框内容的行数
    computeTextAreaLineNum(content) {
      console.log(
        "content = " + content + ",content.length = " + content.length
      );
      var tempCharNum = 0.0;
      var lineCharNum = 15; //每行限制的字符权重数量
      for (var i = 0; i < content.length; i++) {
        var oneChar = (content + "").charAt(i);
        if (/.*[\u4e00-\u9fa5]+.*$/.test(oneChar)) {
          // 是中文
          tempCharNum += 1.0;
        } else if (/.*[A-Z]+.*$/.test(oneChar)) {
          tempCharNum += 1.0;
        } else if (/.*[a-z]+.*$/.test(oneChar)) {
          tempCharNum += 0.4;
        } else if (/.*[0-9]+.*$/.test(oneChar)) {
          tempCharNum += 0.5;
        } else if ("\n" == oneChar) {
          tempCharNum += lineCharNum * 2;
        } else {
          tempCharNum += 1;
        }
      }
      return (
        parseInt(tempCharNum / lineCharNum) +
        (tempCharNum % lineCharNum > 0 ? 1 : 0)
      );
    },

    handleLinechange(detail) {
      console.log("lineCount = " + detail.lineCount);
    },

    handleBoardChange(height) {
      console.log("height", height);
      if (height == 0) {
        this.inputBottom = height;
      } else {
        if (!this.isIOS) {
          this.inputBottom = height - 4;
        } else {
          this.inputBottom = height - 32;
        }
      }
    },
    resetAndCloseMore() {
      console.log(this.isUsualProblems, this.ismore);
    },
    handleBackToMore() {
      this.isUsualProblems = false;
    },
    handleUsualProblemItemClick(item) {
      this.msg = item.title;
      this.updateInputValue(this.msg, {});
    },
    //点击常见问题的时候
    handleUsualProblem() {
      this.isUsualProblems = true;
    },
    //获取高度方法
    getElementHeight() {
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".submit")
        .boundingClientRect((data) => {
          //this.$emit("heights", data.height);
          this.$emit("submitElementRect", data);
        })
        .exec();
    },
    //切换音频
    records() {
      //切换的时候关闭其他界面
      this.ismore = false;
      this.isemoji = false;
      //切换高度
      setTimeout(() => {
        this.getElementHeight();
      }, 10);
      if (this.isrecord) {
        this.isrecord = false;
        this.toc = "https://img3.job1001.com/ypMp/elan/images/common/empty.png";
      } else {
        this.isrecord = true;
        this.toc = "https://img3.job1001.com/ypMp/elan/images/common/empty.png";
      }
    },
    // 表情
    emoji() {
      this.isemoji = !this.isemoji;
      //切换的时候关闭其功能
      this.ismore = false;
      this.isrecord = false;
      this.toc = "https://img3.job1001.com/ypMp/elan/images/common/empty.png";
      //切换高度
      setTimeout(() => {
        this.getElementHeight();
      }, 10);
    },
    //接收表情
    emotion(e) {
      console.log(e), (this.msg = this.msg + e);
    },
    //文字发送
    inputs(e) {
      // var chatm = e.detail.value;
      // var pos = chatm.indexOf("\n");
      // 检索字符串没有数据，返回-1
      // if (pos != -1 && chatm.length > 1) {
      // this.$emit('inputs', this.msg);
      // setTimeout(() => {
      // 	this.msg = '';
      // }, 0)
      // }
      if (this.msg) {
        // 0为表情和文字
        this.send(this.msg, 0);
      }
    },
    handleStop() {
      this.$emit("handleStop");
    },
    //发送
    send(msg, type) {
      let date = {
        message: msg,
        type: type,
      };
      this.$emit("send", date);
      setTimeout(() => {
        this.msg = "";
        // 重新计算标签高度
        this.refreshTextAreaHeight(0);
      }, 0);
    },
    // 输入框聚焦
    focus() {
      //关闭其他项
      this.isemoji = false;
      this.ismore = false;
      this.isUsualProblems = false;
      setTimeout(() => {
        this.getElementHeight();
      }, 10);
    },
    // 表情内发送
    emojiSend() {
      // if (this.msg.length > 0) {
      // 	this.$emit('inputs', this.msg);
      // 	setTimeout(() => {
      // 		this.msg = '';
      // 	}, 0)
      // }

      if (this.msg.length > 0) {
        //0为表情和文字
        this.send(this.msg, 0);
      }
    },
    // 表格退格
    emojiBack() {
      if (this.msg.length > 0) {
        this.msg = this.msg.substring(0, this.msg.length - 1);
      }
    },
    //更多功能
    more() {
      this.ismore = !this.ismore;
      //切换的时候关闭其他界面
      this.isemoji = false;
      this.isrecord = false;
      this.isUsualProblems = false;
      this.toc = "https://img3.job1001.com/ypMp/elan/images/common/empty.png";
      setTimeout(() => {
        this.getElementHeight();
      }, 10);
    },
    //图片发送
    sendImg(e) {
      let count = 9;
      if (e == "album") {
        count = 9;
      } else {
        count = 1;
      }
      uni.chooseImage({
        count: count, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: [e], //从相册选择
        // success: function (res) { //用function的方式会找不到send方法
        success: (res) => {
          console.log(JSON.stringify(res.tempFilePaths));
          const filePaths = res.tempFilePaths;
          for (let i = 0; i < filePaths.length; i++) {
            this.send(filePaths[i], 1);
          }
        },
      });
    },
    //音频处理
    //开始录音
    touchstart(e) {
      console.log("开始录音");
      console.log("点击产生数据", e);
      this.pageY = e.changedTouches[0].pageY;
      this.voicebg = true;
      let i = 1;
      this.timer = setInterval(() => {
        this.vlength = i;
        i++;
        console.log("计时器开始工作,第几秒", i);
        //结束计时
        if (i > 60) {
          clearInterval(this.timer);
          this.touchend();
        }
      }, 1000);
      recorderManager.start();
    },
    //删除录音
    touchmove(e) {
      // console.log("滑动到的y轴高度：",e.changedTouches[0].pageY);
      if (this.pageY - e.changedTouches[0].pageY > 100) {
        // 关闭录音界面
        this.voicebg = false;
      }
    },
    // 结束录音
    touchend() {
      console.log("结束录音");
      clearInterval(this.timer);
      recorderManager.stop();
      // recorderManager.onStop(function(res) {
      recorderManager.onStop((res) => {
        let data = {
          voice: res.tempFilePath,
          time: this.vlength,
        };
        if (this.voicebg) {
          this.send(data, 2);
        }
        // //时长归位
        this.vlength = 0;
        this.voicebg = false;
        console.log("recorder stop" + JSON.stringify(res));
        // self.voicePath = res.tempFilePath;
      });
    },
    //获取位置
    choseLocation() {
      uni.chooseLocation({
        // success: function(res) {
        success: (res) => {
          let data = {
            name: res.name,
            address: res.address,
            latitude: res.latitude,
            longitude: res.longitude,
          };
          this.send(data, 3);
          // console.log('位置名称：' + res.name);
          // console.log('详细地址：' + res.address);
          // console.log('纬度：' + res.latitude);
          // console.log('经度：' + res.longitude);
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base-message: $img-base + "message/";
.submit {
  background: #fff;
  width: 100%;
  position: fixed;
  bottom: 0;
  padding: 0 24rpx;
  // z-index: 100;
  // padding-bottom: var(--status-bar-height);
  padding-bottom: env(safe-area-inset-bottom);
}

.displaynone {
  display: none;
}

.submit-chat {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 14rpx 0rpx;
  .sendBtn {
    text {
    }
  }
  image {
    width: 56rpx;
    height: 56rpx;
    margin: 0 10rpx;
    flex: auto;
  }

  .btn {
    flex: auto;
    background-color: #fff;
    border-radius: 10rpx;
    padding: 20rpx;
    max-height: 160rpx;
    margin: 0 10rpx;
  }
  .msgInput {
    flex: 1;
    margin-right: 24rpx;
    background: #f8f8f8;
    border-radius: 33rpx;
    padding: 8rpx 23rpx;
  }

  ::v-deep .chat-input {
    display: flex;
    align-items: center;
    flex: 1;
    height: 80rpx;
    border-radius: 33rpx;
    background: #f8f8f8;
    position: relative;
    border-radius: 44rpx;
    background: $uni-bg-color-grey;
    overflow: auto;
    margin-right: 24rpx;
    &.lines1 {
      height: 140rpx;
      textarea {
        height: 140rpx;
      }
    }
    &.lines2 {
      height: 180rpx;
      textarea {
        height: 180rpx;
      }
    }
    textarea {
      padding: 24rpx 32rpx;
      height: 88rpx;
      line-height: $uni-font-size-sec;
      font-size: $uni-font-size-base;
      &.clear {
        padding: 24rpx 0 24rpx 32rpx;
      }
    }
    .clear-icon {
      display: flex;
      align-items: center;
      padding: 0 24rpx;
      height: 100%;
    }
  }
  .icon {
    width: 56rpx;
    height: 56rpx;
    background-size: 100% 100%;
    background-size: 100% 100%;
  }
  .icon-emoji {
    margin-right: 20rpx;
    background-image: url($img-base-message + "emoji.png");
  }
  .icon-keyboard {
    margin-right: 20rpx;
    background-image: url($img-base-message + "keyboard.png");
  }
  .icon-more {
    background-image: url("https://img3.job1001.com/xiaolan/images/more.svg");
  }
  .icon-send {
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    background-color: #ff6425;
    width: 106rpx;
    height: 66rpx;
    border-radius: 32rpx;
    background-size: 100% 100%;
  }
  .icon-stop {
    width: 56rpx;
    height: 56rpx;
    background-size: 100% 100%;
    // margin-right: 32rpx;
    background-image: url("https://img3.job1001.com/xiaolan/images/stop.svg");
  }
  .icon-nomore {
    width: 56rpx;
    height: 56rpx;
    background-size: 100% 100%;
    background-image: url("https://img3.job1001.com/xiaolan/images/nomore.png");
  }
  .icon-image {
    background-image: url($img-base-message + "image.png");
  }
  .record {
    line-height: 44rpx;
    text-align: center;
    font-size: 20rpx;
    color: rgba(39, 40, 50, 0.6);
  }
}

.emoji {
  width: 100%;
  height: 460rpx;
  background: rgba(236, 237, 238, 1);
  box-shadow: 0px 11rpx 0px 0px rgba(0, 0, 0, 0.1);

  .emoji-send {
    width: 280rpx;
    height: 104rpx;
    padding-top: 24rpx;
    background-color: rgba(236, 237, 238, 0.8);
    position: fixed;
    // bottom: 0;
    bottom: env(safe-area-inset-bottom);
    right: 0;
    display: flex;

    .emoji-send-bt {
      flex: 1;
      margin: 0 32rpx 0 20rpx;
      height: 80rpx;
      background: rgba(255, 228, 49, 1);
      font-size: 32rpx;
      text-align: center;
      line-height: 80rpx;
      border-radius: 12rpx;
    }

    .emoji-send-det {
      flex: 1;
      margin-left: 24rpx;
      height: 80rpx;
      background: #fff;
      font-size: 32rpx;
      text-align: center;
      line-height: 80rpx;
      border-radius: 12rpx;

      image {
        width: 42rpx;
        height: 32rpx;
      }
    }
  }
}
@keyframes moreAppear {
  from {
    height: 0rpx;
    overflow: hidden;
  }
  to {
    height: 436rpx;
    overflow: scroll;
  }
}
.more {
  width: 100%;
  height: 436rpx;
  background: rgba(255, 255, 255, 1);
  // box-shadow: 0px 11rpx 0px 0px rgba(0, 0, 0, 0.1);
  bottom: env(safe-area-inset-bottom);
  padding: 8rpx 0rpx;
  box-sizing: border-box;
  overflow-y: scroll;
  animation: moreAppear 0.2s linear;
  .more-list {
    width: 25%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    float: left;
    padding-top: 22rpx;
    overflow-y: scroll;
    .moreImageContainer {
      background: rgba(255, 255, 255, 1);
    }
    image {
      width: 124rpx;
      height: 124rpx;
    }
    .more-list-title {
      font-size: 24rpx;
      color: #555;
      line-height: 34rpx;
      margin-top: 20rpx;
    }
  }
  .backToMore {
    font-size: 30rpx;
  }
  .problemList {
    display: flex;
    flex-direction: column;
    color: #555;
    .problemItem {
      font-size: 32rpx;
      padding: 24rpx 4rpx;
      border-bottom: 1px solid #f5f5f5;
    }
  }
}
.higherMore {
  height: 586rpx;
  transition: height 0.1s;
}
.voice-bg {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  position: fixed;
  top: 0;
  bottom: 0;
  z-index: 1001;

  .voice-bg-len {
    height: 84rpx;
    width: 600rpx;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 42rpx;
    text-align: center;
  }

  .voice-bg-time {
    display: inline-block;
    min-width: 120rpx;
    line-height: 84rpx;
    background-color: rgba(255, 228, 49, 1);
    border-radius: 42rpx;
  }

  .voice-del {
    position: absolute;
    bottom: -480rpx;
    width: 100%;
    text-align: center;
    color: #fff;
    font-size: 28rpx;
  }
}
::v-deep .u-input__input .u-input__textarea {
  max-height: 175rpx;
  overflow: scroll;
}
</style>

